package com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.HddcFaultsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.entity.HddcFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.HddcWyFaultsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.HddcWyFaultsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.service.HddcWyFaultsvypointService;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.viewobjects.HddcWyFaultsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.viewobjects.HddcWyFaultsvypointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class HddcWyFaultsvypointServiceImpl implements HddcWyFaultsvypointService {

    private final HddcWyFaultsvypointRepository hddcWyFaultsvypointRepository;
    private final HddcWyFaultsvypointNativeRepository hddcWyFaultsvypointNativeRepository;
    private final HddcFaultsvypointRepository hddcFaultsvypointRepository;
    private final FaultObservationPointExcelVerifyHandler faultObservationPointExcelVerifyHandler;

    @Value("${image.localDir}")
    private String localDir;
    @Value("${image.urlPre}")
    private String urlPre;

    @Autowired
    public HddcWyFaultsvypointServiceImpl(HddcWyFaultsvypointRepository hddcWyFaultsvypointRepository,
                                          HddcWyFaultsvypointNativeRepository hddcWyFaultsvypointNativeRepository,
                                          HddcFaultsvypointRepository hddcFaultsvypointRepository,
                                          FaultObservationPointExcelVerifyHandler faultObservationPointExcelVerifyHandler) {
        this.hddcWyFaultsvypointRepository = hddcWyFaultsvypointRepository;
        this.hddcWyFaultsvypointNativeRepository = hddcWyFaultsvypointNativeRepository;
        this.hddcFaultsvypointRepository = hddcFaultsvypointRepository;
        this.faultObservationPointExcelVerifyHandler = faultObservationPointExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcWyFaultsvypoints(HddcWyFaultsvypointQueryParams queryParams, int curPage, int pageSize) {
        Page<HddcWyFaultsvypointEntity> hddcWyFaultsvypointPage = this.hddcWyFaultsvypointNativeRepository.queryHddcWyFaultsvypoints(queryParams, curPage, pageSize);
        return PlatformPageUtils.formatPageData(hddcWyFaultsvypointPage);
    }


    @Override
    public HddcWyFaultsvypointEntity getHddcWyFaultsvypoint(String uuid) {
        return this.hddcWyFaultsvypointRepository.findById(uuid).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyFaultsvypointEntity saveHddcWyFaultsvypoint(HddcWyFaultsvypointEntity hddcWyFaultsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyFaultsvypoint.setUuid(uuid);
        if (StringUtils.isEmpty(hddcWyFaultsvypoint.getCreateUser())) {
            hddcWyFaultsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyFaultsvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyFaultsvypoint.setIsValid("1");

        HddcFaultsvypointEntity hddcFaultsvypointEntity = new HddcFaultsvypointEntity();
        BeanUtils.copyProperties(hddcWyFaultsvypoint, hddcFaultsvypointEntity);
        hddcFaultsvypointEntity.setExtends4(hddcWyFaultsvypoint.getTown());
        hddcFaultsvypointEntity.setExtends5(String.valueOf(hddcWyFaultsvypoint.getLon()));
        hddcFaultsvypointEntity.setExtends6(String.valueOf(hddcWyFaultsvypoint.getLat()));
        this.hddcFaultsvypointRepository.save(hddcFaultsvypointEntity);

        this.hddcWyFaultsvypointRepository.save(hddcWyFaultsvypoint);
        return hddcWyFaultsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyFaultsvypointEntity updateHddcWyFaultsvypoint(HddcWyFaultsvypointEntity hddcWyFaultsvypoint) {
        HddcWyFaultsvypointEntity entity = hddcWyFaultsvypointRepository.findById(hddcWyFaultsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcWyFaultsvypoint);
        hddcWyFaultsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyFaultsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyFaultsvypointRepository.save(hddcWyFaultsvypoint);
        return hddcWyFaultsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyFaultsvypoints(List<String> ids) {
        List<HddcWyFaultsvypointEntity> hddcWyFaultsvypointList = this.hddcWyFaultsvypointRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcWyFaultsvypointList) && hddcWyFaultsvypointList.size() > 0) {
            this.hddcWyFaultsvypointRepository.deleteAll(hddcWyFaultsvypointList);
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public BigInteger queryHddcWyFaultsvypoint(HddcAppZztCountVo queryParams) {
        return hddcWyFaultsvypointNativeRepository.queryHddcWyFaultsvypoint(queryParams);
    }

    @Override
    public List<HddcWyFaultsvypointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        return hddcWyFaultsvypointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyFaultsvypointEntity> hddcWyFaultsvypointEntity = hddcWyFaultsvypointNativeRepository.exportpoint(queryParams);
        List<HddcWyFaultsvypointVO> list = new ArrayList<>();
        for (HddcWyFaultsvypointEntity entity : hddcWyFaultsvypointEntity) {
            HddcWyFaultsvypointVO hddcWyFaultsvypointVO = new HddcWyFaultsvypointVO();
            BeanUtils.copyProperties(entity, hddcWyFaultsvypointVO);
            list.add(hddcWyFaultsvypointVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "断层观测点-点", "断层观测点-点", HddcWyFaultsvypointVO.class, "断层观测点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(faultObservationPointExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcWyFaultsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyFaultsvypointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcWyFaultsvypointVO hddcWyFaultsvypointVO : result.getFailList()) {
                    returnMsg.append("第").append(hddcWyFaultsvypointVO.getRowNum()).append("行").append(hddcWyFaultsvypointVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcWyFaultsvypointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcWyFaultsvypointVO> list) {
        for (HddcWyFaultsvypointVO wyFaultsvypointVO : list) {
            HddcWyFaultsvypointEntity hddcWyFaultsvypointEntity = new HddcWyFaultsvypointEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(wyFaultsvypointVO, hddcWyFaultsvypointEntity);
            saveHddcWyFaultsvypoint(hddcWyFaultsvypointEntity);
        }
    }

    @Override
    public List<HddcWyFaultsvypointEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        return hddcWyFaultsvypointRepository.findAllByCreateUserAndIsValid(userId, isValid);
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyFaultsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyFaultsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyFaultsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyFaultsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyFaultsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyFaultsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyFaultsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyFaultsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }
}
